package com.launcher.factory;

import java.util.ArrayList;
import java.util.List;

import com.launcher.AdvancedRocket;
import com.launcher.PayLoad;
import com.launcher.Rocket;
import com.launcher.RocketService;
import com.launcher.decorator.AdvancedEngine;
import com.launcher.decorator.AdvancedFairring;
import com.launcher.decorator.AdvancedStage;
import com.launcher.decorator.Engine;
import com.launcher.decorator.Fairring;
import com.launcher.decorator.RocketTop;
import com.launcher.decorator.Stage;

public class AdvancedRocketFactory extends RocketFactory
{
	public AdvancedRocketFactory()
	{
		super();
	}
	
	@Override
	public Rocket createRocket(PayLoad payload)
	{
		if (payload == null)
		{
			return null;
		}
		
		Rocket r = new AdvancedRocket();
		r = new RocketTop(r, payload);
		
		Fairring f = RocketService.getInstance().getFairring(payload.getHeight());
		f.setRocketDecorator(r);
		int mass = payload.getMass() * 10 + f.getMass() * 100;
		List<Engine> engines = RocketService.getInstance().getEnginesHL();

		List<Engine> list = new ArrayList<Engine>();
		Engine engine = engines.get(engines.size() - 1);
		int power = engine.getPower();
		mass += engine.getMass() + engine.getRocketDecorator().getMass();
		list.add(engine);
		
		list = getCheapestEngineCombination(list, engines, power, mass);
		
		r = f;
		for (Engine e : list)
		{
			((Stage) e.getRocketDecorator()).setRocketDecorator(r);
			r = e;
		}
		
		return r;
	}
	
	@Override
	public AdvancedFairring createFairring(int cost, int mass, int capability)
	{
		AdvancedFairring fairring = new AdvancedFairring();
		fairring.setCost(cost);
		fairring.setMass(mass);
		fairring.setCapability(capability);
		
		RocketService.getInstance().saveRocket(fairring);
		
		return fairring;
	}

	@Override
	public AdvancedEngine createEngine(int cost, int power)
	{
		AdvancedEngine engine = new AdvancedEngine();
		engine.setCost(cost);
		engine.setPower(power);
		
		RocketService.getInstance().saveRocket(engine);
		
		return engine;
	}

	@Override
	public AdvancedStage createStage(int cost, int mass, int height)
	{
		AdvancedStage stage = new AdvancedStage();
		stage.setCost(cost);
		stage.setMass(mass);
		stage.setHeight(height);
		
		RocketService.getInstance().saveRocket(stage);
		
		return stage;
	}
}
